package cn.com.anypay.manager.controller.sdk;

import cn.com.anypay.manager.config.AlipayConfig;
import cn.com.anypay.manager.config.WxpayConfig;
import cn.com.anypay.manager.dto.QrcodeParams;
import cn.com.anypay.manager.service.UserAuthService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 聚合静态码入口控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/qrcode/entry") // 暂定API路径，可以根据实际情况调整
public class QrcodeEntryController {

    @Autowired
    @Qualifier("alipayUserAuthServiceImpl")
    private UserAuthService userAuthService;

    @Autowired
    @Qualifier("wxpayUserAuthServiceImpl")
    private UserAuthService wxUserAuthService;

    @Autowired
    private AlipayConfig alipayConfig;

    @Autowired
    private WxpayConfig wxpayConfig;

    /**
     * 根据qrcode获取二维码关联的支付参数信息
     *
     * @param qrcode 二维码ID
     * @return QrcodeParams 包含支付所需参数的对象
     */
    @GetMapping
    public QrcodeParams getQrCodeParams(@RequestParam("qrcode") String qrcode) {
        log.info("收到获取二维码参数请求, qrcode: {}", qrcode);

        // TODO: 实现根据 qrcode 查询数据库或配置，获取真实的二维码信息
        // 以下为模拟数据，实际项目中需要替换为真实的业务逻辑

        if (qrcode == null || qrcode.trim().isEmpty()) {
            log.warn("Qrcode parameter is missing or empty");
            // 可以抛出自定义异常或返回错误信息的 QrcodeParams
            // 例如: throw new IllegalArgumentException("qrcode不能为空");
            // 或者返回一个带有错误标识的 QrcodeParams 对象
            QrcodeParams errorParams = new QrcodeParams();
            errorParams.setPageType("ERROR");
            errorParams.setProductDescription("无效的二维码ID");
            return errorParams;
        }

        // 模拟根据qrcode查找数据
        QrcodeParams params = new QrcodeParams();
        if ("QR2025060310001".equals(qrcode)) { // 假设这是用户提供的示例qrcode
            // 普通商户模式
            String alipayAppId = alipayConfig.getMchApp().getAppId();
            String wxpayAppId = wxpayConfig.getMp().getAppId();

            params.setMerchantId("MCH000001");
            params.setMerchantName("示例商户-后端");
            params.setPaymentMethods(Arrays.asList("WECHAT_PAY", "ALIPAY"));
            params.setWechatAppId(wxpayAppId);
            params.setAlipayAppId(alipayAppId);
            params.setNormalMerchantMode(true);
            params.setPaymentChannel("LESHUA_MOCK");
            params.setChannelMerchantId("LESHUA_MCH_ID_123");
            params.setOrderAmount(new BigDecimal("0.01")); // 模拟金额
            params.setProductDescription("聚合码收款-后端模拟");
            params.setNotifyUrl("https://yourdomain.com/api/payment/notify/leshua");
            params.setAttach("custom_attach_data_from_backend");
        } else if ("QR2025060310002".equals(qrcode)) {
            params.setMerchantId("MCH000002");
            params.setMerchantName("支付宝小程序商户-后端");
            params.setPaymentMethods(Arrays.asList("ALIPAY"));
            params.setAlipayMiniProgramId("alipay_mini_program_id_backend");
            params.setNormalMerchantMode(false); // 服务商模式
            params.setSubMchId("SUB_MCH_ALIPAY_002");
            params.setPaymentChannel("ALIPAY_DIRECT_MOCK");
            params.setChannelMerchantId("ALIPAY_DIRECT_MCH_ID_456");
            params.setProductDescription("支付宝小程序收款-后端模拟");
            params.setNotifyUrl("https://yourdomain.com/api/payment/notify/alipay_direct");
        } else {
            log.warn("No configuration found for qrcode: {}", qrcode);
            // 返回表示未找到配置的参数，或者抛出异常
            QrcodeParams notFoundParams = new QrcodeParams();
            notFoundParams.setProductDescription("二维码信息未配置: " + qrcode);
            return notFoundParams;
        }

        log.info("Returning QrcodeParams: {}", params);
        return params;
    }

    /**
     * 获取授权URL
     *
     * @param qrcode 二维码ID
     * @param env 环境标识（alipay/wechat/unionpay/qq）
     * @param redirectUri 授权回调地址
     * @return 包含授权URL的响应
     */
    @GetMapping("/auth/url")
    public Map<String, Object> getAuthUrl(
            @RequestParam("qrcode") String qrcode,
            @RequestParam("env") String env,
            @RequestParam("redirectUri") String redirectUri) {
        log.info("收到获取授权链接请求, qrcode: {}, env: {}, redirectUri: {}", qrcode, env, redirectUri);

        Map<String, Object> response = new HashMap<>();
        String envLower = env.toLowerCase();

        try {
            // 1. 获取二维码参数
            QrcodeParams params = getQrCodeParams(qrcode);
            if (params == null || "ERROR".equals(params.getPageType()) || "NOT_FOUND".equals(params.getPageType())) {
                response.put("code", 400);
                response.put("message", "无效的二维码ID");
                return response;
            }

            // 2. 先对 redirectUri 进行 URL 解码
            String decodedRedirectUri = java.net.URLDecoder.decode(redirectUri, java.nio.charset.StandardCharsets.UTF_8.name());

            // 3. 根据环境构建授权URL
            String authUrl;
            if ("alipay".equals(envLower)) {
                if (params.getAlipayAppId() == null) {
                    response.put("code", 400);
                    response.put("message", "该二维码不支持支付宝支付");
                    return response;
                }
                authUrl = userAuthService.buildAuthUrl(params.getAlipayAppId(), decodedRedirectUri);
            } else if ("wechat".equals(envLower)) {
                if (params.getWechatAppId() == null) {
                    response.put("code", 400);
                    response.put("message", "该二维码不支持微信支付");
                    return response;
                }
                authUrl = wxUserAuthService.buildAuthUrl(params.getWechatAppId(), decodedRedirectUri);
            } else {
                response.put("code", 400);
                response.put("message", "不支持的环境类型: " + env);
                return response;
            }

            // 4. 返回授权URL
            response.put("code", 0);
            response.put("message", "success");
            response.put("data", Map.of(
                "authUrl", authUrl,
                "env", envLower
            ));

        } catch (Exception e) {
            log.error("获取授权URL失败", e);
            response.put("code", 500);
            response.put("message", "获取授权URL失败: " + e.getMessage());
        }

        return response;
    }

    /**
     * 获取支付宝buyerId
     *
     * @param qrcode 二维码ID
     * @param auth_code 授权码
     * @return 包含buyerId的响应
     */
    @GetMapping("/alipay/buyerid")
    public Map<String, Object> getAlipayBuyerId(
            @RequestParam("qrcode") String qrcode,
            @RequestParam("auth_code") String auth_code) {
        log.info("=== 获取支付宝buyerId开始 ===");
        log.info("二维码ID: {}, 授权码: {}", qrcode, auth_code);

        try {
            // 1. 获取二维码参数
            QrcodeParams params = getQrCodeParams(qrcode);
            if (params == null || "ERROR".equals(params.getPageType()) || "NOT_FOUND".equals(params.getPageType())) {
                return Map.of(
                    "code", 400,
                    "message", "无效的二维码ID"
                );
            }

            // 2. 验证是否支持支付宝支付
            if (params.getAlipayAppId() == null) {
                return Map.of(
                    "code", 400,
                    "message", "该二维码不支持支付宝支付"
                );
            }

            // 3. 获取buyerId
            Map<String, Object> tokenInfo = userAuthService.exchangeAuthCodeForToken(
                params.getAlipayAppId(),
                auth_code,
                alipayConfig.getMchApp().getPrivateKey()
            );

            String buyerId = (String) tokenInfo.get("user_id");
            log.info("获取buyerId成功: buyerId={}", buyerId);

            return Map.of(
                "code", 0,
                "message", "success",
                "data", Map.of(
                    "buyerId", buyerId,
                    "qrcode", qrcode
                )
            );
        } catch (Exception e) {
            log.error("获取支付宝buyerId失败: {}", e.getMessage(), e);
            return Map.of(
                "code", -1,
                "message", "获取支付宝buyerId失败: " + e.getMessage()
            );
        }
    }

    /**
     * 获取微信buyerId
     *
     * @param qrcode 二维码ID
     * @param code 授权码
     * @return 包含buyerId的响应
     */
    @GetMapping("/wechat/buyerid")
    public Map<String, Object> getWechatBuyerId(
            @RequestParam("qrcode") String qrcode,
            @RequestParam("code") String code) {
        log.info("=== 获取微信buyerId开始 ===");
        log.info("二维码ID: {}, 授权码: {}", qrcode, code);

        try {
            // 1. 获取二维码参数
            QrcodeParams params = getQrCodeParams(qrcode);
            if (params == null || "ERROR".equals(params.getPageType()) || "NOT_FOUND".equals(params.getPageType())) {
                return Map.of(
                    "code", 400,
                    "message", "无效的二维码ID"
                );
            }

            // 2. 验证是否支持微信支付
            if (params.getWechatAppId() == null) {
                return Map.of(
                    "code", 400,
                    "message", "该二维码不支持微信支付"
                );
            }

            // 3. 获取access_token和openid
            Map<String, Object> tokenInfo = wxUserAuthService.exchangeAuthCodeForToken(
                params.getWechatAppId(),
                code,
                wxpayConfig.getMp().getSecret()
            );

            String accessToken = (String) tokenInfo.get("access_token");
            String openId = (String) tokenInfo.get("openid");

            // 4. 获取用户信息
            Map<String, Object> userInfo = wxUserAuthService.getUserProfile(
                openId,
                accessToken,
                wxpayConfig.getMp().getSecret()
            );

            String unionId = (String) userInfo.get("unionid");
            log.info("获取微信用户信息成功: unionId={}", unionId);

            return Map.of(
                "code", 0,
                "message", "success",
                "data", Map.of(
                    "buyerId", unionId != null ? unionId : openId,
                    "qrcode", qrcode
                )
            );
        } catch (Exception e) {
            log.error("获取微信buyerId失败: {}", e.getMessage(), e);
            return Map.of(
                "code", -1,
                "message", "获取微信buyerId失败: " + e.getMessage()
            );
        }
    }
}